package pl.edu.mimuw.irs.core.model.design.resource;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.Collection;
import java.util.LinkedHashSet;

public class Resources extends LinkedHashSet<Resource> implements IHolder<Resource>, PropertyChangeListener {

	private static final long serialVersionUID = -1687675896004951400L;

	// *** Properties
	public static final String RESOURCE = "RESOURCE";
	
	// *** Attributes

	private PropertyChangeSupport listeners;
	public PropertyChangeSupport getListeners() {
		if (listeners == null) listeners = new PropertyChangeSupport(this);
		return listeners;
	}
	
	// *** Methods
	
	@Override
	public boolean add(Resource e) {
		boolean retval = super.add(e);
		if (retval) {
			e.setResources(this);
			e.addPropertyChangeListener(this);
			getListeners().firePropertyChange(RESOURCE, null, e);
		}
		
		return retval;
	}
	
	@Override
	@Deprecated
	public boolean addAll(Collection<? extends Resource> c) {
		throw new UnsupportedOperationException();
	}
	
	@Override
	public boolean remove(Object o) {
		boolean retval = super.remove(o);
		if (o instanceof Resource) {
			Resource resource = (Resource) o;
			getListeners().firePropertyChange(RESOURCE, resource, null);
			if (resource.getResources() == this) resource.setResources(null);
			resource.removePropertyChangeListener(this);
		}
		return retval;
	}

	@Override
	public boolean remove(Resource o) {
		return this.remove((Object) o);
	}

	@Override
	@Deprecated
	public boolean removeAll(Collection<?> c) {
		throw new UnsupportedOperationException();
	}
	
	@Override
	@Deprecated
	public boolean retainAll(Collection<?> c) {
		throw new UnsupportedOperationException();
	}
	
	public void addPropertyChangeListener(PropertyChangeListener listener) {
		getListeners().addPropertyChangeListener(listener);
	}
	
	public void removePropertyChangeListener(PropertyChangeListener listener) {
		getListeners().removePropertyChangeListener(listener);
	}
	
	@Override
	public void propertyChange(PropertyChangeEvent arg0) {
		getListeners().firePropertyChange(arg0);
	}
}
